#include <iostream>
#include "../../common/etcd.h"
#include "../../common/channel.h"
#include <gflags/gflags.h>
#include <thread>
#include <functional>
#include "../brpc/main.pb.h"


DEFINE_bool(run_mode, false, "程序的运行模式，false-调试； true-发布；");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(call_service, "/service/echo", "服务监控根目录");
void callback(brpc::Controller* cntl, ::example::EchoResponse* response)
{
	std::unique_ptr<brpc::Controller> cntl_guard(cntl);
	std::unique_ptr<example::EchoResponse> res_guard(response);
	if (cntl->Failed())
	{
		std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
		return;
	}
	std::cout << "收到响应: " << response->message() << std::endl;
}
int main(int argc, char* argv[])
{
	google::ParseCommandLineFlags(&argc, &argv, true);
	Init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);
	//架构rpc通信通道
	auto sm = std::make_shared<ServiceManager>();
	sm->declared(FLAGS_call_service);
	auto put_cb = std::bind(&ServiceManager::onServiceOnline, sm.get(), std::placeholders::_1, std::placeholders::_2);
	auto del_cb = std::bind(&ServiceManager::onServiceOffline, sm.get(), std::placeholders::_1, std::placeholders::_2);
	//创建服务发现对象
	Discovery::ptr discovery = std::make_shared<Discovery>(FLAGS_etcd_host, FLAGS_base_service, put_cb, del_cb);
	//创建channel，获取信道
	auto channel = sm->choose(FLAGS_base_service);
	if (!channel)
	{
		std::this_thread::sleep_for(std::chrono::seconds(1));
		return -1;
	}
	//发起调用
	example::EchoService_Stub stub(channel.get());
	example::EchoRequest req;
	req.set_message("hello word");
	//
	brpc::Controller* cntl = new brpc::Controller();
	example::EchoResponse* rsp = new example::EchoResponse();
	//同步调用
	stub.Echo(cntl, &req, rsp, nullptr);
	if (cntl->Failed() == true) {
		std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
		delete cntl;
		delete rsp;
		std::this_thread::sleep_for(std::chrono::seconds(1));
		//continue;
	}
	std::cout << "收到响应: " << rsp->message() << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(1));
	return 0;
}